<template>
    <section class="coversation">
		<div class="pic-box" v-show="bigPic.show" @click="showPic('toClose')">
			<img :src="bigPic.src">
		</div>
		<div class="coversationlist">
			<div class="underscore">
				dfjdsjgodf
			</div> 
			<ul>
				<li v-for="item in dataArr" v-if="item.transData[0].type!='tip'">
					<div class="other" :class="{mysay : item.fromAccount == loginInfo.identifier }">
						<img src=" " class="head"> 
						<div class="whatsay">
							<div class="whatsay_text"> 
								<div v-for="subItem in item.transData" class="say-box">
									<div v-if="subItem.type=='text'">{{subItem.text}}</div>
									<div v-if="subItem.type=='face'" class="face">
										<img :src="subItem.faceUrl">
									</div>
									<div v-if="subItem.type=='img'" class="small-img">
										<img :src="subItem.smallImage" @click.stop="showPic('toShow',subItem.bigImage)">
									</div>
								</div>
							</div>
						</div>
					</div>
				</li>	
				<li v-else>{{item.transData[0].text}}</li>
			</ul>
		</div>
		<div class="send-box">
			<section v-if="emotions">
				<ul class="face-pack">
					<li v-for="item in emotions" @click="sendFace(item[0])"><img :src="item[1]"></li>
				</ul>
			</section>
			<section class="main-bar">
				<div class="content-box"><input id="inputText" /></div>
				<div class="btn" @click.stop="onSendMsg()">发送</div>
				<div class="pic" @click.stop="sendPic()" style="position:relative">
					图片
					<input type="file" id="upd_pic" @change="sendPic($event)" style="opacity:0;position:absolute;top:0;left:0">
				</div>
				
			</section>
		</div>
    </section>
</template>

<script>
import $ from 'jquery';
import Chat from '../../config/chat';
import Client from '../../config/common';
import convertMsgtoHtml from '../../config/convertMsg';
export default {
    data(){
        return{
			friendId:Client.getQueryString('id'),
			urlType:Client.getQueryString('selType'),
			selType:Client.getQueryString('selType'),//会话类型 C2C或GROUP
			loginInfo:{},
			dataArr:[],
			bigPic:{src:'',show:false},//大图
			emotions:null//表情
        }
    },
    created(){
		Client.login((loginInfo) => {
			 this.loginInfo = loginInfo;
			 if(this.selType == 'C2C'){
				this.selType = webim.SESSION_TYPE.C2C;
				this.getLastC2CHistoryMsgs();
			}else{
				this.selType = webim.SESSION_TYPE.GROUP;
				this.getLastGroupHistoryMsgs();
			}
		});
		
	},
	mounted(){
		this.emotions = webim.Emotions;
		console.log(webim.Emotions);
    },

    components:{
       
    },

    computed:{

    },

    methods:{
		 //获取最新的c2c历史消息,用于切换好友聊天，重新拉取好友的聊天消息
		getLastC2CHistoryMsgs(cbOk, cbError){
			/*if (selType == webim.SESSION_TYPE.GROUP) {
				alert('当前的聊天类型为群聊天，不能进行拉取好友历史消息操作');
				return;
			}*/
			let lastMsgTime = 0;//第一次拉取好友历史消息时，必须传0
			let msgKey = '';
			let options = {
				'Peer_Account': this.friendId, //好友帐号
				'MaxCnt': 10, //拉取消息条数
				'LastMsgTime': lastMsgTime, //最近的消息时间，即从这个时间点向前拉取历史消息
				'MsgKey': msgKey
			};
			webim.getC2CHistoryMsgs(
					options,
					(resp) => {
						let complete = resp.Complete;//是否还有历史消息可以拉取，1-表示没有，0-表示有
						let retMsgCount = resp.MsgCount;//返回的消息条数，小于或等于请求的消息条数，小于的时候，说明没有历史消息可拉取了
						if (resp.MsgList.length == 0) {
							webim.Log.error("没有历史消息了:data=" + JSON.stringify(options));
							return;
						}
						/*getPrePageC2CHistroyMsgInfoMap[selToID] = {//保留服务器返回的最近消息时间和消息Key,用于下次向前拉取历史消息
							'LastMsgTime': resp.LastMsgTime,
							'MsgKey': resp.MsgKey
						};*/

						//数据处理
						//console.log('test',convertMsgtoHtml(resp.MsgList[1]))
						let oldArr = resp.MsgList;
						//let newArr = [];
						oldArr.forEach((arr,index) => {
							let trans = convertMsgtoHtml(arr);
							oldArr[index].transData = trans;
						});
						this.dataArr = oldArr;
						//console.log('this.dataArr',oldArr);
						//设置消息已读
						let selSess = webim.MsgStore.sessByTypeId(this.selType, this.friendId);
						webim.setAutoRead(selSess, true, true);

						if (cbOk)
							cbOk(resp.MsgList);
					},
					cbError
					);
		},
		//获取最新的群历史消息,用于切换群组聊天时，重新拉取群组的聊天消息
	    getLastGroupHistoryMsgs(cbOk) {
			if (selType == webim.SESSION_TYPE.C2C) {
				alert('当前的聊天类型为好友聊天，不能进行拉取群历史消息操作');
				return;
			}
	    let selType = this.selType;
		let selToID = this.friendId;
		let reqMsgCount = 20; //每次请求的历史消息(c2c获取群)条数
		let selSess = webim.MsgStore.sessByTypeId(selType, selToID);
		let recentSessMap = {}; //保存最近会话列表
		let getPrePageGroupHistroyMsgInfoMap = {}; //保留下一次拉取群历史消息的信息
		Chat.getGroupInfo(selToID, (resp) => {
			//拉取最新的群历史消息
			var options = {
				'GroupId': selToID,
				'ReqMsgSeq': resp.GroupInfo[0].NextMsgSeq - 1,
				'ReqMsgNumber': reqMsgCount
			};
			if (options.ReqMsgSeq == null || options.ReqMsgSeq == undefined || options.ReqMsgSeq <= 0) {
				webim.Log.warn("该群还没有历史消息:options=" + JSON.stringify(options));
				return;
			}
			//selSess = null;
			webim.MsgStore.delSessByTypeId(selType, selToID);
			recentSessMap[webim.SESSION_TYPE.GROUP + "_" + selToID] = {};

			recentSessMap[webim.SESSION_TYPE.GROUP + "_" + selToID].MsgGroupReadedSeq = resp.GroupInfo && resp.GroupInfo[0] && resp.GroupInfo[0].MsgSeq;
			webim.syncGroupMsgs(
				options,
				(msgList) => {
					if (msgList.length == 0) {
						webim.Log.warn("该群没有历史消息了:options=" + JSON.stringify(options));
						return;
					}
					var msgSeq = msgList[0].seq - 1;
					getPrePageGroupHistroyMsgInfoMap[selToID] = {
						"ReqMsgSeq":  msgSeq
					};
					//数据解析
					console.log(msgList);
						//let newArr = [];
						msgList.forEach((arr,index) => {
							let trans = convertMsgtoHtml(arr);
							msgList[index].transData = trans;
						});
					this.dataArr = msgList;
					webim.setAutoRead(selSess, true, true);
					//清空聊天界面
					//document.getElementsByClassName("msgflow")[0].innerHTML = "";
					if (cbOk){
						cbOk(msgList);
					}
						
				},
				(err) => {
					alert(err.ErrorInfo);
				}
			);
		});
	},
		//*****以下为好友或群组通用收发消息方法*****
		//发送消息(文本或者表情)
		onSendMsg() {
			let selType = this.selType; //当前聊天类型
			let selToID = this.friendId; //当前选中聊天id（当聊天类型为私聊时，该值为好友帐号，否则为群号）
			//let selSess = webim.MsgStore.sessByTypeId(selType, selToID);//获取当前回话
			let friendHeadUrl = '';
			if (!selToID) {
				alert("你还没有选中好友或者群组，暂不能聊天");
				return;
			}
			//获取消息内容
			let msgtosend = document.querySelector('#inputText').value;
			let msgLen = webim.Tool.getStrBytes(msgtosend);
			
			if (msgtosend.length < 1) {
				alert("发送的消息不能为空!");
				return;
			}
			let maxLen, errInfo;
			if (selType == webim.SESSION_TYPE.C2C) {
				maxLen = webim.MSG_MAX_LENGTH.C2C;
				errInfo = "消息长度超出限制(最多" + Math.round(maxLen / 3) + "汉字)";
			} else {
				maxLen = webim.MSG_MAX_LENGTH.GROUP;
				errInfo = "消息长度超出限制(最多" + Math.round(maxLen / 3) + "汉字)";
			}
			if (msgLen > maxLen) {
				alert(errInfo);
				return;
			}

			//if (selSess) {
			//	alert('369')
			let selSess = new webim.Session(selType, selToID, selToID, friendHeadUrl, Math.round(new Date().getTime() / 1000));
			//}
			let isSend = true;//是否为自己发送
			let seq = -1;//消息序列，-1表示sdk自动生成，用于去重
			let random = Math.round(Math.random() * 4294967296);//消息随机数，用于去重
			let msgTime = Math.round(new Date().getTime() / 1000);//消息时间戳
			let subType;//消息子类型
			if (selType == webim.SESSION_TYPE.C2C) {
				subType = webim.C2C_MSG_SUB_TYPE.COMMON;
			}else{
				//webim.GROUP_MSG_SUB_TYPE.COMMON-普通消息,
				//webim.GROUP_MSG_SUB_TYPE.LOVEMSG-点赞消息，优先级最低
				//webim.GROUP_MSG_SUB_TYPE.TIP-提示消息(不支持发送，用于区分群消息子类型)，
				//webim.GROUP_MSG_SUB_TYPE.REDPACKET-红包消息，优先级最高
				subType = webim.GROUP_MSG_SUB_TYPE.COMMON;
			}
			console.log('selSess',selSess);
			let msg = new webim.Msg(selSess, isSend, seq, random, msgTime, this.loginInfo.identifier, subType, this.loginInfo.identifierNick);
			let text_obj, face_obj, tmsg, emotionIndex, emotion, restMsgIndex;
			//解析文本和表情
			let expr = /\[[^[\]]{1,3}\]/mg;
			let emotions = msgtosend.match(expr);
			if (!emotions || emotions.length < 1) {
				text_obj = new webim.Msg.Elem.Text(msgtosend);
				msg.addText(text_obj);
			} else {

				for (let i = 0; i < emotions.length; i++) {
					tmsg = msgtosend.substring(0, msgtosend.indexOf(emotions[i]));
					if (tmsg) {
						text_obj = new webim.Msg.Elem.Text(tmsg);
						msg.addText(text_obj);
					}
					emotionIndex = webim.EmotionDataIndexs[emotions[i]];
					emotion = webim.Emotions[emotionIndex];

					if (emotion) {
						face_obj = new webim.Msg.Elem.Face(emotionIndex, emotions[i]);
						msg.addFace(face_obj);
					} else {
						text_obj = new webim.Msg.Elem.Text(emotions[i]);
						msg.addText(text_obj);
					}
					restMsgIndex = msgtosend.indexOf(emotions[i]) + emotions[i].length;
					msgtosend = msgtosend.substring(restMsgIndex);
				}
				if (msgtosend) {
					text_obj = new webim.Msg.Elem.Text(msgtosend);
					msg.addText(text_obj);
				}
			}

			webim.sendMsg(msg, (resp) => {
				if (selType == webim.SESSION_TYPE.C2C) {//私聊时，在聊天窗口手动添加一条发的消息，群聊时，长轮询接口会返回自己发的消息
					//addMsg(msg);
				}
				webim.Tool.setCookie("tmpmsg_" + selToID, '', 0);
				console.log('msg',msg);

				//数据解析			
				let addTranslate = convertMsgtoHtml(msg);
				msg.transData = addTranslate;
				console.log('666',msg);

				//群聊时，长轮询接口会返回自己发的消息
				if(this.selType != 'GROUP'){
					this.dataArr.push(msg);
				}
				document.querySelector('#inputText').value = '';
				//turnoffFaces_box();隐藏表情框
			}, function (err) {
				alert(err.ErrorInfo);
				//$("#send_msg_text").val('');
			});
		},
		showPic(type,src){
			if(type=='toClose'){
				this.bigPic.src = '0';
				this.bigPic.show = false;
			}else{
				this.bigPic.src = src;
				this.bigPic.show = true;
			}
			
		},
		sendFace(text){
			let inputBox = document.querySelector("#inputText");
			inputBox.value += text;
		},
		//上传并发送图片
		sendPic(event){
			let uploadFiles = document.getElementById('upd_pic');
			if (!window.File || !window.FileList || !window.FileReader) {
				alert("您的浏览器不支持File Api");
				return;
			}
			if(uploadFiles.value ==''){
				return;
			}
			console.log('有图片');
			let file = uploadFiles.files[0];
			let fileSize = file.size;
			//先检查图片类型和大小
			if (!this.checkPic(uploadFiles, fileSize)) {
				return;
			}
			//上传图片
				let businessType;//业务类型，1-发群图片，2-向好友发图片
				if (this.selType == webim.SESSION_TYPE.C2C) {//向好友发图片
					businessType = webim.UPLOAD_PIC_BUSSINESS_TYPE.C2C_MSG;
				} else if (this.selType == webim.SESSION_TYPE.GROUP) {//发群图片
					businessType = webim.UPLOAD_PIC_BUSSINESS_TYPE.GROUP_MSG;
				}
				//封装上传图片请求
				let opt = {
					'file': file, //图片对象
					'onProgressCallBack': this.onProgressCallBack, //上传图片进度条回调函数
					//'abortButton': document.getElementById('upd_abort'), //停止上传图片按钮
					'From_Account': this.loginInfo.identifier, //发送者帐号
					'To_Account': this.friendId, //接收者
					'businessType': businessType//业务类型
				};

				//上传图片
				webim.uploadPic(opt,
						(resp) => {
							//上传成功发送图片
                            this.postPic(resp,file.name);
						},
						(err) => {
							alert(err.ErrorInfo);
						}
				);
		},
		//上传图片回调
		onProgressCallBack(loadedSize, totalSize){
			console.log('loadedSize',loadedSize);
			console.log('totalSize',totalSize);
		},
		//检查文件类型和大小
        checkPic(obj, fileSize) {
			let picExts = 'jpg|jpeg|png|bmp|gif|webp';
			let photoExt = obj.value.substr(obj.value.lastIndexOf(".") + 1).toLowerCase();//获得文件后缀名
			let pos = picExts.indexOf(photoExt);
			if (pos < 0) {
				alert("您选中的文件不是图片，请重新选择");
				return false;
			}
			fileSize = Math.round(fileSize / 1024 * 100) / 100; //单位为KB
			if (fileSize > 30 * 1024) {
				alert("您选择的图片大小超过限制(最大为30M)，请重新选择");
				return false;
			}
			return true;
		},
		//上传成功后发送图片消息
		postPic(images,imgName) {
			if (!this.friendId) {
				alert("您还没有好友，暂不能聊天");
				return;
			}

			if (!this.selSess) {
				this.selSess = new webim.Session(this.selType, this.friendId, this.friendId, '', Math.round(new Date().getTime() / 1000));
			}
			let msg = new webim.Msg(this.selSess, true, -1, -1, -1, this.loginInfo.identifier, 0, this.loginInfo.identifierNick);
			let images_obj = new webim.Msg.Elem.Images(images.File_UUID);
			for (let i in images.URL_INFO) {
				let img = images.URL_INFO[i];
				let newImg;
				let type;
				switch (img.PIC_TYPE) {
					case 1://原图
						type = 1;//原图
						break;
					case 2://小图（缩略图）
						type = 3;//小图
						break;
					case 4://大图
						type = 2;//大图
						break;
				}
				newImg = new webim.Msg.Elem.Images.Image(type, img.PIC_Size, img.PIC_Width, img.PIC_Height, img.DownUrl);
				images_obj.addImage(newImg);
			}
			msg.addImage(images_obj);
			//if(imgName){
			//    let data=imgName;//通过自定义消息中的data字段保存图片名称
			//    let custom_obj = new webim.Msg.Elem.Custom(data, '', '');
			//    msg.addCustom(custom_obj);
			//}
			//调用发送图片消息接口
			webim.sendMsg(msg, (resp)=> {
				if (this.selType == webim.SESSION_TYPE.C2C) {//私聊时，在聊天窗口手动添加一条发的消息，群聊时，长轮询接口会返回自己发的消息
					console.log('图片最终发送成功',msg);
					//解析回传的图片信息
					let translatePic = convertMsgtoHtml(msg);
					msg.transData = translatePic;
					this.dataArr.push(msg);
					document.getElementById('upd_pic').value = '';
				}
			}, function (err) {
				alert(err.ErrorInfo);
			});
		}
    },
	watch:{
          'loginInfo.onMsgNotify':function(val){  
			  if(val == null || val == {}){
				  console.log('空对象',val)
				  return
			  }else{
				let listenNew = convertMsgtoHtml(val);
				val.transData = listenNew;
				this.dataArr.push(val);
			  }
            }  
	},
}

</script>

<style lang="scss"> 
@import '../../style/public';
.coversation{
	    height:100%;
		background-color: #ebebeb;
		-webkit-overflow-scrolling: touch; 
		.pic-box{
			width:100%;
			height:100%;
			position:fixed;
			z-index:99999;
			background:rgba(0,0,0,.8);
			display:-webkit-box;
			-webkit-box-orient: vertical;
            -webkit-box-align: center;
            -webkit-box-pack: center;
			img{
				max-width:100%;
			}
		}
		.coversationlist{
			position: relative;
			padding:0 .15rem;
			overflow:auto;
			margin:0 auto;
			.underscore{
				padding-top:0.2rem;
				text-align:center;
				//@include sizeColor(0.5546666667rem,#999);
			}
			ul{
				padding-top:.4rem;
				padding-bottom:4.2rem;
				width:100%;
				overflow-scrolling: touch; 
				-webkit-overflow-scrolling: touch; 
				top:0;
				li{
					.other{
						width:100%;
						@include justify(flex-start);
						margin-bottom:.21rem;
						align-items:top;
						img.head{
							display:block;
							@include widthHeight(.4rem,.4rem);
						}
						.whatsay{
							position: relative;
							.whatsay_svg{
								@include widthHeight(0.4266666667rem,0.64rem);
								position: absolute;
								top:.5546667rem;
								left:.36rem;
								z-index:2;
								svg{
									display:block;
									@include widthHeight(0.4266666667rem,0.64rem);
								}
							}
							
							.whatsay_text{
								margin-left:.1rem;
								/*max-width:8.2rem;*/
								background:#fff;
								padding:.1rem .15rem;
								border:1px solid #d9d9d9;
								border-radius:8px;
								@include sizeColor(0.4rem, #333);
								line-height:0.2rem;
								word-break: break-all;
								.say-box{
									display:inline-block;
									font-size: .14rem;
									color:#fff;
									.face{
										width:.2rem;
										img{
											width:100%;
											height:.2rem;
										}
								    }
								}
								
							}
						}
						
					}
					.mysay{
						display:flex;
						flex-direction:row-reverse;
						.whatsay{
							.whatsay_text{
								margin-right:.1rem;
								margin-left:0;
								background:#9fe658;
							}
						}
					}
				}
			}
			
		}
		.send-box{
			padding:.2rem;
			position:fixed;
			bottom:0;
			left:0;
			background-color: #fff;
			.main-bar{
				display: -webkit-box;
				width:100%;
				height:1.4rem;
				.content-box{
					-webkit-box-flex: 1.0;
					#inputText{
						display:block;
						width:100%;
						height:1rem;
						border:1px solid #ccc;
						padding-left:.2rem;
						border-radius:.1rem;
					}
				}
				.btn{
					width:1.6rem;
					height:1rem;
					vertical-align: middle;
					margin-left:.2rem;
					background:#eaeaea;
					border:1px solid #ccc;
				}
			}
			.face-pack{
				li{
					display: inline-block;
				}
			}
		}
	}
</style>